<template>
  <a-card :bordered="false">
    <a-row :gutter="8">
      <a-col :span="5"><search-tree :treeData="deptTree" :dataList="dataList" :expandedKeys="expandedKeys" :holderText="holderText" @select="handleSelect"></search-tree></a-col>
      <a-col :span="19">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :md="5" :sm="15">
                <a-form-item label="工号"><a-input placeholder="请输入工号" v-model="queryParam.jobNumber" /></a-form-item>
              </a-col>
              <a-col :md="5" :sm="15">
                <a-form-item label="教师姓名"><a-input placeholder="请输入教师姓名" v-model="queryParam.name" /></a-form-item>
              </a-col>
              <a-col :md="5" :sm="15">
                <a-form-item label="职称">
                  <a-select placeholder="请选择职称" v-model="queryParam.jobTitle" allowClear>
                    <a-select-option v-for="(b, index) in jobTitleList" :key="index" :value="b.dictValue">{{ b.dictLabel }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <span class="table-page-search-submitButtons">
                  <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                  <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div class="table-operator">
          <a-button v-if="addEnable" type="primary" icon="plus" @click="$refs.modal.add()">新建</a-button>
          <a-button v-if="addEnable" icon="plus" @click="createLogin">批量创建教师帐号</a-button>
          <a-dropdown v-if="removeEnable && selectedRowKeys.length > 0">
            <a-popconfirm
              title="确定删除吗?"
              ok-text="是"
              cancel-text="否"
              @confirm="delByIds(selectedRowKeys)"
            >
              <a-button type="danger" icon="delete" >删除</a-button>
            </a-popconfirm>
           </a-dropdown>
        </div>
        <s-table
          size="default"
          ref="table"
          rowKey="teacherId"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          :columns="columns"
          :data="loadData">
          <span slot="jobTitle" slot-scope="text">{{ text | jobTitleFilter }}</span>
          <span slot="action" slot-scope="text, record">
            <a v-if="editEnabel" @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
             <a-popconfirm
               title="确定删除吗?"
               ok-text="是"
               cancel-text="否"
               @confirm="delByIds([record.teacherId])"
             >
              <a v-if="removeEnable" >删除</a>
            </a-popconfirm>

          </span>
        </s-table>
      </a-col>
    </a-row>

    <teacher-modal
      ref="modal"
      @ok="handleOk"
      :genderList="genderList"
      :nationList="nationList"
      :politicalStatusList="politicalStatusList"
      :jobTitleList="jobTitleList"
      :deptTree="deptTree"
    />
  </a-card>
</template>

<script>
import { STable, SearchTree } from '@/components'
import { getTcTeacherList, delTcTeacher } from '@/api/teacher'
import { getDeptListEnable, createTeachers } from '@/api/system'
import TeacherModal from './modules/TeacherModal.vue'
import { checkPermission } from '@/utils/permissions'
import { getDictArray } from '@/utils/dict'
const jobTitleMap = {}
export default {
  name: 'TableList',
  components: {
    STable,
    TeacherModal,
    SearchTree
  },
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      form: this.$form.createForm(this),
      mdl: {},
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '工号',
          dataIndex: 'jobNumber'
        },
        {
          title: '教师姓名',
          dataIndex: 'name'
        },
        {
          title: '电话号码',
          dataIndex: 'telphone'
        },
        {
          title: '部门',
          dataIndex: 'deptName'
        },
        {
          title: '职称',
          dataIndex: 'jobTitle',
          scopedSlots: { customRender: 'jobTitle' }
        },
        {
          title: '操作',
          width: '200px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return getTcTeacherList(Object.assign(parameter, this.queryParam))
      },
      selectedRowKeys: [],
      selectedRows: [],
      addEnable: checkPermission('system:teacher:add'),
      editEnabel: checkPermission('system:teacher:edit'),
      removeEnable: checkPermission('system:teacher:remove'),
      genderList: [],
      nationList: [],
      politicalStatusList: [],
      jobTitleList: [],

      deptTree: [],
      expandedKeys: [],
      dataList: [],
      holderText: '搜索部门'
    }
  },
  filters: {
    jobTitleFilter (type) {
      return jobTitleMap[type]
    }
  },
  created () {
    getDeptListEnable().then(res => {
      const data = res.rows
      this.buildtree(data, this.deptTree, 0)
      this.expandedKeys = data.map(m => m.parentId)
      this.dataList = data.map(m => {
        return { key: m.deptId, title: m.deptName }
      })
    })
    getDictArray('sys_user_sex').then(res => {
      this.genderList = res
    })
    getDictArray('st_nation').then(res => {
      this.nationList = res
    })
    getDictArray('political_status').then(res => {
      this.politicalStatusList = res
    })
    getDictArray('job_title').then(res => {
      this.jobTitleList = res
      res.map(item => {
        jobTitleMap[item.dictValue] = item.dictLabel
      })
      console.log(jobTitleMap)
    })
  },
  methods: {
    createLogin () {
      console.log('批量创建帐号')
      createTeachers().then(res => {
        console.log(res)
        if (res.code === 0) {
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleAdd () {
      this.$refs.modal.add()
    },
    handleEdit (record) {
      this.$refs.modal.edit(record)
    },
    handleOk () {
      this.$refs.table.refresh(true)
      console.log('handleSaveOk')
    },
    delByIds (ids) {
      delTcTeacher({ ids: ids.join(',') }).then(res => {
        if (res.code === 0) {
          this.$message.success('删除成功')
          this.handleOk()
        } else {
          this.$message.error(res.msg)
        }
        this.selectedRowKeys = []
      })
    },
    buildtree (list, arr, parentId) {
      list.forEach(item => {
        if (item.parentId === parentId) {
          var child = {
            key: item.deptId,
            value: item.deptId, // value是给modal的select用的，2者属性不一样
            title: item.deptName,
            scopedSlots: { title: 'title' },
            children: []
          }
          this.buildtree(list, child.children, item.deptId)
          if (child.children.length === 0) {
            delete child.children
          }
          arr.push(child)
        }
      })
    },
    // 下面是树相关方法
    handleSelect (selectedKeys, info) {
      this.queryParam = {
        deptId: selectedKeys[0]
      }
      this.$refs.table.refresh(true)
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
